package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.dto.bpa.ContractInfoDto;
import top.infopub.dto.bpa.PrimarySureDto;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.bpa.SureContractTypeEnum;
import top.infopub.enums.bpa.SureTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.bpa.dao.BpaPrimarySureDao;
import top.infopub.mgr.bpa.dao.PrimarySureDetailDao;
import top.infopub.mgr.bpa.jsonVo.PrimarySureJsonVo;
import top.infopub.mgr.bpa.service.BpaPrimarySureService;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.vo.BpaPrimarySureVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.model.bpa.PrimarySure;
import top.infopub.model.bpa.PrimarySureDetail;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wurz on 2021/6/10.
 */
@Service
public class BpaPrimarySureServiceImpl implements BpaPrimarySureService {
    @Resource
    private BpaPrimarySureDao bpaPrimarySureDao;

    @Autowired
    private PrimarySureDetailDao primarySureDetailDao;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private BpaProcessManageService bpaProcessManageService;

    @Override
    public Page<BpaPrimarySureVo> selectList(Page<BpaPrimarySureVo> page, BpaPrimarySureVo bpaPrimarySure) throws ParseException {
        //处理时间范围
        if (!StringUtils.isEmpty(bpaPrimarySure.getDates())) {
            String[] splitTime = bpaPrimarySure.getDates().split("~");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            bpaPrimarySure.setMonthBegin(format.parse(splitTime[0]));
            bpaPrimarySure.setMonthEnd(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return bpaPrimarySureDao.selectList(bpaPrimarySure);
    }

    @Override
    public Integer getCount(BpaPrimarySureVo bpaPrimarySure) {
        int count = bpaPrimarySureDao.selectCount(bpaPrimarySure);
        return count;
    }

    @Override
    public PrimarySureJsonVo queryDetailById(String id) {
        PrimarySureJsonVo priSureJson = new PrimarySureJsonVo();
        if (StringUtils.isNotBlank(id)) {
            PrimarySureDto priSureDto = new PrimarySureDto();
            //查询产值确权详情
            PrimarySure priSure = bpaPrimarySureDao.selectOne(id);
            BeanUtils.copyProperties(priSure, priSureDto);
            priSureDto.setContractTypeName(SureContractTypeEnum.getByCode(priSureDto.getSureType()).getName());
            //查询项目基础信息
            BpaPublicProInfoDto proInfoDto = projectInfoService.queryBpaProInfoByProCode(priSure.getProCode());
            BeanUtils.copyProperties(proInfoDto, priSureDto);
            priSureJson.setInfo(priSureDto);
            //查询详情列表
            List<PrimarySureDetail> detailList = primarySureDetailDao.queryByPrimarySureId(id);
            priSureJson.setDetailList(detailList);
            //文件列表
            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, this.getFileType(priSure.getSureType()), null);
            priSureJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
            //合同列表
            List<ContractInfoDto> contractInfoList = getContrInfoByType(priSure.getSureType(), priSure.getProCode());
            priSureJson.setContractInfoList(contractInfoList);
        } else {
            priSureJson.setProInfoList(setupProService.queryPublicProInfo());
        }
        return priSureJson;
    }

    @Override
    public PrimarySureJsonVo queryProInfoByProCode(String proCode) {
        PrimarySureJsonVo priSureJson = new PrimarySureJsonVo();
        PrimarySureDto priSureDto = new PrimarySureDto();
        //查询项目基础信息
        BpaPublicProInfoDto proInfoDto = projectInfoService.queryBpaProInfoByProCode(proCode);
        BeanUtils.copyProperties(proInfoDto, priSureDto);
        priSureJson.setInfo(priSureDto);
        return priSureJson;
    }

    @Override
    public PrimarySureJsonVo queryContractInfo(String proCode, String sureType) {
        PrimarySureJsonVo priSureJson = new PrimarySureJsonVo();
        PrimarySureDto priSureDto = new PrimarySureDto();
        priSureDto.setContractType(SureContractTypeEnum.getByCode(sureType).getCode());
        priSureDto.setContractType(SureContractTypeEnum.getByCode(sureType).getName());
        priSureJson.setInfo(priSureDto);
        //合同列表
        List<ContractInfoDto> contractInfoList = getContrInfoByType(sureType, proCode);
        priSureJson.setContractInfoList(contractInfoList);
        return priSureJson;
    }

    private List<ContractInfoDto> getContrInfoByType(String sureType, String proCode) {
        List<ContractInfoDto> list = null;
        if (SureTypeEnum.DEVICE.getCode().equals(sureType)){
            list = bpaPrimarySureDao.queryContractInfoList("BPA_DEVICE_COT", proCode);
        }else if (SureTypeEnum.OTHER.getCode().equals(sureType)){
            list = bpaPrimarySureDao.queryContractInfoList("BPA_OTHER_CONTRACTS_REVIEW", proCode);
        }else if (SureTypeEnum.PACKAGE.getCode().equals(sureType)){
            list = bpaPrimarySureDao.queryContractInfoList("BPA_SUBPACK_COT", proCode);
        }else if (SureTypeEnum.INCAE.getCode().equals(sureType)){
            list = bpaPrimarySureDao.queryContractInfoList("BPA_INNER_AGRT", proCode);
        }else if(SureTypeEnum.OUTCAE.getCode().equals(sureType)){
            list = bpaPrimarySureDao.queryContractInfoList("BPA_CONTRACT_NEG", proCode);
        }
        return list;
    }

    private String getFileType(String sureType){
        String fileType = null;
        if (SureTypeEnum.DEVICE.getCode().equals(sureType)){
            fileType = ProjectFileTypeEnum.FILE_TYPE120.getCode();
        }else if (SureTypeEnum.OTHER.getCode().equals(sureType)){
            fileType = ProjectFileTypeEnum.FILE_TYPE123.getCode();
        }else if (SureTypeEnum.PACKAGE.getCode().equals(sureType)){
            fileType = ProjectFileTypeEnum.FILE_TYPE117.getCode();
        }else if (SureTypeEnum.INCAE.getCode().equals(sureType)){
            fileType = ProjectFileTypeEnum.FILE_TYPE114.getCode();
        }else if(SureTypeEnum.OUTCAE.getCode().equals(sureType)){
            fileType = ProjectFileTypeEnum.FILE_TYPE111.getCode();
        }
        return fileType;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RspVo edit(PrimarySureJsonVo priSureJson, Integer submitType, AuthorizationVO vo) {
        String id = priSureJson.getInfo().getId();
        PrimarySure tmpPriSure = new PrimarySure();
        PrimarySure priSure = new PrimarySure();
        BeanUtils.copyProperties(priSureJson.getInfo(), priSure);
        priSure.setUptBy(vo.getId());
        priSure.setUptTime(new Date());
        priSure.setContractType(priSure.getSureType());
        if (StringUtils.isNotBlank(id)) {
            //校验
            tmpPriSure = bpaPrimarySureDao.selectOne(id);
            if (tmpPriSure == null) return RspVo.getFailureResponse(400, "产值确权数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(tmpPriSure.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPriSure.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpPriSure.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            bpaPrimarySureDao.updateByPrimaryKey(priSure);
        } else {
            //新增
            priSure.setCodes(IdFactory.getUUIDUpper());
            priSure.setAddBy(vo.getId());
            priSure.setAddTime(new Date());
            //新增主表数据
            bpaPrimarySureDao.insert(priSure);
        }

        //处理子表数据
        List<PrimarySureDetail> detailList = priSureJson.getDetailList();
        primarySureDetailDao.deleteByPrimarySureId(priSure.getId());
        if (detailList != null && detailList.size() > 0) {
            int index = 1;
            for (PrimarySureDetail detail : detailList) {
                if (detail == null) continue;
                detail.setPrimarySureId(priSure.getId());
                detail.setAddBy(vo.getId());
                detail.setAddTime(new Date());
                detail.setSeq(index);
                primarySureDetailDao.insert(detail);
            }
        }

        //更新附件表-MKT_PROJECT_ATTACHMENT--该处ID映射好
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(priSureJson.getFileAtt()!=null){
            String[] fileAtt = priSureJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(priSure.getId(), file);
                attachmentList.add(attachment);
            }
        }
        //更新附件信息--根据不同类型的ProjectFileTypeEnum处理附件信息
        projectAttachmentDao.deleteByWhere(priSure.getId(), this.getFileType(priSure.getSureType()), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType == 1) {
            //处理OA待办，主表里的OA_ID
            if (StringUtils.isNotBlank(tmpPriSure.getOaId())) {
                oaFlowService.finishOA(tmpPriSure.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(priSure.getId()));
            //根据不同类型发起不同的流程，参考BpaProcessDetailTypeEnum
            bpaProcessManageService.sendProcess(this.getProByType(priSure.getSureType()), detailJson, priSure.getId(), priSure.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    private BpaProcessDetailTypeEnum getProByType(String sureType){
        if (SureTypeEnum.DEVICE.getCode().equals(sureType)){
            return BpaProcessDetailTypeEnum.PRO_NODE_TYPE21;
        }else if (SureTypeEnum.OTHER.getCode().equals(sureType)){
            return BpaProcessDetailTypeEnum.PRO_NODE_TYPE22;
        }else if (SureTypeEnum.PACKAGE.getCode().equals(sureType)){
            return BpaProcessDetailTypeEnum.PRO_NODE_TYPE20;
        }else if (SureTypeEnum.INCAE.getCode().equals(sureType)){
            return BpaProcessDetailTypeEnum.PRO_NODE_TYPE19;
        }else if(SureTypeEnum.OUTCAE.getCode().equals(sureType)){
            return BpaProcessDetailTypeEnum.PRO_NODE_TYPE18;
        }
        return null;
    }

    @Override
    public PrimarySure selectOne(String id) {
        return bpaPrimarySureDao.selectOne(id);
    }
}
